﻿
using System.Linq.Expressions;
using Simple.Common.Authentication;
using Simple.Services.System;
using Simple.Services.System.FileInfo;

namespace Simple.Services
{
    public class LeaveMessageService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;
        private readonly FileInfoService _fileInfoService;

        public LeaveMessageService(SimpleDbContext context,
            ISimpleService services,
            FileInfoService fileInfoService) : base(services)
        {
            _context = context;
            _fileInfoService = fileInfoService;
        }

        public async Task<List<LeaveMessageModel>> GetAsync()
        {
            var lstChildrens = (await OrganizationFilter(_context.Set<ClassDynamicLeaveMessage>())).ToList();
            return MapperHelper.Map<List<LeaveMessageModel>>(lstChildrens);
        }

        public async Task<PageResultModel<LeaveMessageModel>> GetPageAsync(LeaveMessagePageInputModel input)
        {
            if (_currentUser == null || !_currentUser.UserId.HasValue)
            {
                throw AppResultException.Status409Conflict("登录过期，请重新登录!");
            }

            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            LoginType? loginType = null;
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                loginType = (LoginType)Enum.Parse(typeof(LoginType), loginTypeValue);
            }

            var result = new PageResultModel<LeaveMessageModel>();
            var query = await OrganizationFilter(_context.Set<ClassDynamicLeaveMessage>().Include(p => p.Replys).Include(p => p.ClassDynamic));

            // 根据条件查询
            if (!string.IsNullOrEmpty(input.Name))
            {
                query = query.Where(m => EF.Functions.Like(m.LeaveMessageContent, $"%{input.Name}%"));
            }

            if (!string.IsNullOrEmpty(input.ParentName))
            {
                query = query.Where(m => EF.Functions.Like(m.LeaveMessageUserName, $"%{input.ParentName}%"));
            }

            if (!string.IsNullOrWhiteSpace(input.ClassDynamicId))
            {
                Guid.TryParse(input.ClassDynamicId, out var _classDynamicId);
                query = query.Where(u => u.ClassDynamicId == _classDynamicId);
            }

            if ((loginType != null && loginType != LoginType.ParentSide) || loginType == null)
            {
                //老师
                var currentClassAuthorizationList = await GetClassAuthorizationInfo();
                if (currentClassAuthorizationList == null || !currentClassAuthorizationList.Any())
                {
                    throw AppResultException.Status409Conflict("未找到授权班级，请联系管理员授权班级后再试!");
                }

                if (currentClassAuthorizationList != null && currentClassAuthorizationList.Any())
                {
                    var classIdList = currentClassAuthorizationList.Select(c => c.Id)?.ToList();
                    if (!string.IsNullOrEmpty(input.ClassId))
                    {
                        Guid.TryParse(input.ClassId, out var _currentClassId);
                        if (!classIdList.Any(c => c == _currentClassId))
                        {
                            throw AppResultException.Status409Conflict($"未授权的班级Id：【{_currentClassId}】，请联系管理员授权班级后再试!");
                        }
                        query = query.Where(u => u.ClassId == _currentClassId);
                    }
                }
            }

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.OrderByDescending(u => u.CreatedTime).Page(input.PageNo, input.PageSize);
            var lstLeaveMessage = await query.ToListAsync();
            var lstLeaveMessageDto = MapperHelper.Map<List<LeaveMessageModel>>(lstLeaveMessage);
            if (lstLeaveMessageDto != null)
            {
                var currentClassIdList = lstLeaveMessage?.Where(c => c.ClassId.HasValue).Select(p => p.ClassId);
                var lstClass = (await OrganizationFilter(_context.Set<SysClasses>().Where(p => currentClassIdList.Contains(p.Id))))?.ToList();
                var _childIdList = lstLeaveMessage?.Where(c => c.RelationshipChildrenId.HasValue)?.Select(c => c.RelationshipChildrenId)?.ToList();
                List<Childrens>? chidrenList = new List<Childrens>();
                if (_childIdList != null && _childIdList.Any())
                {
                    chidrenList = _context.Set<Childrens>().Where(c => _childIdList.Contains(c.Id))?.ToList();
                }

                foreach (var leaveMessage in lstLeaveMessageDto)
                {
                    if (leaveMessage.ClassId.HasValue)
                    {
                        var classes = lstClass?.FirstOrDefault(p => p.Id == leaveMessage.ClassId);
                        if (classes != null)
                        {
                            leaveMessage.ClassName = classes.Name;
                        }
                    }

                    leaveMessage.RelationshipChildrenName = chidrenList?.FirstOrDefault(p => p.Id == leaveMessage.RelationshipChildrenId)?.Name ?? string.Empty;
                }
            }

            result.Rows = lstLeaveMessageDto;

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        public async Task<int> AddAsync(LeaveMessageInputModel model)
        {
            if (_currentUser == null)
            {
                throw AppResultException.Status409Conflict("登录已过期，请重新登录!");
            }

            var leaveMessage = MapperHelper.Map<ClassDynamicLeaveMessage>(model);
            leaveMessage.LeaveMessageTime = DateTime.Now;
            leaveMessage.LeaveMessageUserId = _currentUser?.FindClaimValue(SimpleClaimTypes.UserId);
            leaveMessage.LeaveMessageUserName = _currentUser?.FindClaimValue(SimpleClaimTypes.UserName);
            leaveMessage.LeaveMessageUserImageId = _currentUser?.FindClaimValue(SimpleClaimTypes.CurrentUserImageId);

            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                Enum.TryParse(typeof(LoginType), loginTypeValue, out var _loginTypeValue);
                if (_loginTypeValue != null)
                {
                    leaveMessage.LoginType = ((LoginType)_loginTypeValue).GetHashCode();
                }

                if (((LoginType)_loginTypeValue) == LoginType.ParentSide)
                {
                    //家长端
                    var parent = await (await OrganizationFilter(_context.Set<Parent>())).FirstOrDefaultAsync(c => c.Id == _currentUser.UserId);
                    if (parent != null && parent.ImgId.HasValue && !string.IsNullOrWhiteSpace(leaveMessage.LeaveMessageUserImageId))
                    {
                        Guid.TryParse(leaveMessage.LeaveMessageUserImageId, out var parentImageId);
                        if (parent.ImgId != parentImageId)
                        {
                            leaveMessage.LeaveMessageUserImageId = parent.ImgId.ToString();
                        }
                    }
                }
                else if (((LoginType)_loginTypeValue) == LoginType.GardenSide)
                {
                    //园务端
                    leaveMessage.LeaveMessageUserImageId = await _fileInfoService.GetUserPortrait(_currentUser.UserId.Value);
                }
            }

            var relationshipValue = _currentUser?.FindClaimValue(SimpleClaimTypes.Relationship);
            if (!string.IsNullOrWhiteSpace(relationshipValue))
            {
                Enum.TryParse(typeof(EnumParentRelationship), relationshipValue, out var _relationshipValue);
                if (_relationshipValue != null)
                {
                    leaveMessage.Relationship = ((EnumParentRelationship)_relationshipValue).GetHashCode();
                }
            }
            var childIdValue = _currentUser?.FindClaimValue(SimpleClaimTypes.ChildId);
            Guid.TryParse(childIdValue, out Guid chidrenId);
            leaveMessage.RelationshipChildrenId = chidrenId;

            var classesIdValue = _currentUser?.FindClaimValue(SimpleClaimTypes.ClassesId);
            if (!string.IsNullOrWhiteSpace(classesIdValue))
            {
                Guid.TryParse(classesIdValue, out var _currentClassId);
                leaveMessage.ClassId = _currentClassId;
            }

            await _context.AddAsync(leaveMessage);

            var _currentMyLeaveMessageList = (await OrganizationFilter(_context.Set<ClassDynamicLeaveMessage>())).Where(c => c.CreatedUserId == _currentUser.UserId)?.ToList();
            if (_currentMyLeaveMessageList != null && _currentMyLeaveMessageList.Any() && !string.IsNullOrWhiteSpace(leaveMessage.LeaveMessageUserImageId))
            {
                _currentMyLeaveMessageList?.ForEach(c =>
                {
                    c.LeaveMessageUserImageId = leaveMessage.LeaveMessageUserImageId;
                });

                _context.UpdateRange(_currentMyLeaveMessageList);
            }
            return await _context.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(IEnumerable<Guid> ids)
        {
            var lstChild = await _context.Set<ClassDynamicLeaveMessage>()
                .Where(u => ids.Contains(u.Id))
                .ToListAsync();

            _context.RemoveRange(lstChild);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 恢复/屏蔽
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> IsPublish(IsPublishDto input)
        {
            var child = await _context.Set<ClassDynamicLeaveMessage>()
                .FirstOrDefaultAsync(p => p.Id.ToString() == input.LeaveMessageId);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到留言，更新失败");
            }
            child.IsPublish = input.IsPublish;
            _context.Update(child);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取当前登录用户授权的班级
        /// </summary>
        /// <returns></returns>
        public async Task<List<ClassesModel>> GetClassAuthorizationInfo()
        {
            if (_currentUser == null)
            {
                throw AppResultException.Status409Conflict("登录已过期，请重新登录!");
            }

            var query = await OrganizationFilter(_context.Set<SysClasses>());
            if (!_currentUser.IsSuperAdmin)
            {
                query = query.Where(c => c.TeacherIds.Contains(_currentUser.UserId.ToString()));
            }

            var authorizationClassList = await query.ToListAsync();
            if (authorizationClassList == null || !authorizationClassList.Any())
            {
                return new List<ClassesModel>();
            }

            return MapperHelper.Map<List<ClassesModel>>(authorizationClassList);
        }

        /// <summary>
        /// 我的留言
        /// </summary>
        /// <returns></returns>
        public async Task<PageResultModel<LeaveMessageModel>> MoveLeaveMessageGetPageAsync(MoveLeaveMessagePageInputModel input)
        {
            if (_currentUser == null || !_currentUser.UserId.HasValue)
            {
                throw AppResultException.Status409Conflict("登录过期，请重新登录!");
            }

            var loginTypeValue = _currentUser?.FindClaimValue(SimpleClaimTypes.LoginType);
            LoginType? loginType = null;
            if (!string.IsNullOrWhiteSpace(loginTypeValue))
            {
                loginType = (LoginType)Enum.Parse(typeof(LoginType), loginTypeValue);
            }

            var classIdList = new List<string>();
            if (loginType != null)
            {
                if (loginType == LoginType.GardenSide)
                {
                    //老师
                    var currentClassAuthorizationList = await GetClassAuthorizationInfo();

                    if (currentClassAuthorizationList != null && currentClassAuthorizationList.Any())
                    {
                        classIdList = currentClassAuthorizationList.Select(c => c.Id.ToString() ?? string.Empty).Where(c => !string.IsNullOrWhiteSpace(c)).ToList();
                    }
                }
                else if (loginType == LoginType.ParentSide)
                {
                    //家长
                    var _currentClassId = _currentUser?.FindClaimValue(SimpleClaimTypes.ClassesId);
                    if (!string.IsNullOrWhiteSpace(_currentClassId))
                    {
                        if (_currentClassId?.Contains(',') ?? false)
                        {
                            classIdList = _currentClassId?.Split(',')?.ToList();
                        }
                        else
                        {
                            classIdList.Add(_currentClassId);
                        }
                    }
                }
            }

            var classDynamicLeaveMessageQuery = from c in (await OrganizationFilter(_context.Set<ClassDynamic>().Where(p => p.CreatedUserId == _currentUser.UserId).Include(p => p.LeaveMessages).Include(p => p.Images))).SelectMany(c => c.LeaveMessages) select c;
            // 根据条件查询
            if (!string.IsNullOrEmpty(input.LeaveMessageContent))
            {
                classDynamicLeaveMessageQuery = classDynamicLeaveMessageQuery.Where(m => EF.Functions.Like(m.LeaveMessageContent, $"%{input.LeaveMessageContent}%"));
            }

            var _currentClassIdList = classIdList?.Select(p => Guid.Parse(p)).ToList();
            if (_currentClassIdList != null && _currentClassIdList.Any())
            {
                classDynamicLeaveMessageQuery = classDynamicLeaveMessageQuery.Where(u => _currentClassIdList.Contains(u.ClassId.Value));
            }

            var result = new PageResultModel<LeaveMessageModel>();
            
            // 获取总数量
            result.TotalRows = await classDynamicLeaveMessageQuery.CountAsync();

            // 分页查询
            var giveMeClassDynamicLeaveMessageQuery = classDynamicLeaveMessageQuery.OrderByDescending(c => c.CreatedTime).Page(input.PageNo, input.PageSize);
            var lstLeaveMessage = await giveMeClassDynamicLeaveMessageQuery.ToListAsync();

            var _childIdList = lstLeaveMessage.Select(c => c.RelationshipChildrenId)?.Where(c => c != default(Guid))?.ToList();
            List<Childrens>? chidrenList = new List<Childrens>();
            if (_childIdList != null && _childIdList.Any())
            {
                chidrenList = _context.Set<Childrens>().Where(c => _childIdList.Contains(c.Id))?.ToList();
            }

            var lstLeaveMessageDto = MapperHelper.Map<List<LeaveMessageModel>>(lstLeaveMessage);
            if (lstLeaveMessageDto != null)
            {
                var lstClass = (await OrganizationFilter(_context.Set<SysClasses>()))?.ToList();
                foreach (var leaveMessage in lstLeaveMessageDto)
                {
                    if (leaveMessage.ClassId.HasValue)
                    {
                        var classes = lstClass?.FirstOrDefault(p => p.Id == leaveMessage.ClassId);
                        if (classes != null)
                        {
                            leaveMessage.ClassName = classes.Name;
                        }
                    }

                    leaveMessage.RelationshipChildrenName = chidrenList?.FirstOrDefault(p => p.Id == leaveMessage.RelationshipChildrenId)?.Name ?? string.Empty;
                }
            }

            result.Rows = lstLeaveMessageDto;
            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }
    }
}
